import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { Form, Input, Button, Checkbox } from "antd";
import { push, goBack } from "react-router-redux";
import style from "./style.less";
import ThirdLogin from "../ThirdLogin";
import ErrTip from "../ErrTip";
import { loginByName } from "../../services/api/user";
import { postLoginRequest } from "../../actions";
import { errCode } from "../../helper/errCode";
const FormItem = Form.Item;

class LoginCode extends PureComponent {
  state = {
    _name: ["username", "password", "captcha"],
    keys: 2,
    _rules: [
      [{ required: true, message: <ErrTip>请输入手机号/邮箱/用户名</ErrTip> }],
      [{ required: true, message: <ErrTip>请输入密码</ErrTip> }],
      [{ required: true, message: <ErrTip>请输入图形验证码</ErrTip> }]
    ],
    _placeholder: [
      "请输入手机号/邮箱/用户名",
      "请输入密码",
      "请输入图形验证码"
    ],
    _type: ["string", "password", "string"],
    errInfo: "",
    timeStamp: "",
    imgCode: ""
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) return;
      delete values.keys;
      loginByName({
        request_from: 1,
        return_type: "sync_json",
        is_store_login: values.remember ? 1 : 0,
        ...values
      }).then(data => {
        const response = data.data && data.data.data;
        const flag = String(response.flag);
        if (flag !== "0") {
          console.log(flag, errCode[flag]);

          this.changeImgCode();

          if (flag === "2012" || flag === "2011") {
            return this.addImgCode();
          } else if (flag === "5101") {
            this.props.form.resetFields(["password", "captcha"]);
            this.props.form.setFields({
              captcha: {
                value: "",
                errors: [new Error("图形验证码错误")]
              }
            });
          } else {
            this.props.form.resetFields(["password", "captcha"]);
            return this.props.form.setFields({
              password: {
                value: "",
                errors: [new Error("账号或者密码错误")]
              }
            });
          }
        } else {
          console.log(response, this.props);
          window.location.href = "http://my.veryeast.cn";
        }
      });
    });
  };

  addImgCode = () => {
    const { form } = this.props;
    const keys = form.getFieldValue("keys");
    if (keys.indexOf(2) > -1) return;
    const nextKeys = keys.concat(2);
    form.setFieldsValue({
      keys: nextKeys
    });
  };

  onChangeValue = e => {
    const value = e.target.value;
    this.setState({
      imgCode: value
    });
  };

  changeImgCode = () => {
    let date = new Date();
    let timeStamp = date.getTime();
    this.setState({ timeStamp });
  };

  render() {
    const { _name, _rules, _placeholder, _type, timeStamp } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    getFieldDecorator("keys", { initialValue: [0, 1] });
    const keys = getFieldValue("keys");
    const formItems = keys.map(k => {
      return k < 2 ? (
        <FormItem key={k}>
          <div className={style.formItem}>
            {getFieldDecorator(`${_name[k]}`, {
              rules: _rules[k]
            })(
              <Input
                className={style.formInput}
                placeholder={_placeholder[k]}
                type={_type[k]}
                onFocus={this.clearErr}
              />
            )}
          </div>
        </FormItem>
      ) : (
        <FormItem key={k}>
          <div className={style.formItem}>
            <div className={style.codeWrap}>
              {getFieldDecorator(`${_name[k]}`, {
                rules: _rules[k]
              })(
                <Input
                  className={`${style.formInput} ${style.code}`}
                  placeholder={_placeholder[k]}
                  type={_type[k]}
                  onFocus={this.clearErr}
                />
              )}
              <div className={style.imgCode} onClick={this.changeImgCode}>
                <img src={`/u/captcha?t=${timeStamp}`} alt="" />
              </div>
            </div>
          </div>
        </FormItem>
      );
    });

    return (
      <div className={style.loginCard}>
        <Form onSubmit={this.handleSubmit} className={style.login}>
          {formItems}
          <FormItem>
            {getFieldDecorator("remember", {
              valuePropName: "checked",
              initialValue: true
            })(<Checkbox>下次自动登录</Checkbox>)}
            <a
              className={style.loginForgot}
              onClick={() => this.props.navigateTo("/forgetPassword")}
            >
              忘记密码?
            </a>
            <div className={style.loginBtn}>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
              >
                登 录
              </Button>
            </div>
            <div className={style.register}>
              没有帐号？{" "}
              <a onClick={() => this.props.navigateTo("/register")}>
                立即注册？
              </a>
            </div>
          </FormItem>
        </Form>
        <ThirdLogin />
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    loginCode: state.user.data
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    navigateTo: location => {
      dispatch(push(location));
    },
    goBack: () => {
      dispatch(goBack());
    },
    login: payload => {
      dispatch(postLoginRequest(payload));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(
  Form.create({
    onChange: this.onChangeValue
  })(LoginCode)
);
